package com.yojcodesendbox.codesendbox;

import com.yojcodesendbox.constant.ResponseCodeEnum;
import com.yojcodesendbox.model.ExecuteCodeRequest;
import com.yojcodesendbox.model.ExecuteCodeResponse;
import com.yojcodesendbox.model.ExecuteResult;
import com.yojcodesendbox.model.JudgeInfo;
import com.yojcodesendbox.util.ProcessUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Data
@Component
public class ExecuteCodeTemplate extends CodeSandbox {


    @Autowired
    ProcessUtil processUtil;


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        ExecuteCodeResponse exeCodeRes = new ExecuteCodeResponse();

        String code = executeCodeRequest.getCode();
        List<String> inputList = executeCodeRequest.getInputList();

       processUtil.writeCodeToFile(code, fileTail);
        // 获取用户代码文件路径
        String userCodeFilePath = processUtil.getUserCodeFilePath();
        // 获取用户代码文件目录路径
        String userCodeDir = processUtil.getUserCodeDir();
        String compileCmdStr = compilCmd.replace("%s", userCodeDir);
        // 编译
        ExecuteResult exeCompilRes = processUtil.executeCompilCmd(compileCmdStr, null);

        if (exeCompilRes.getCode() == 1) {
            System.out.println("编译错误：" + exeCompilRes);
            exeCodeRes.setStatus(ResponseCodeEnum.COMPILE_ERR.getCode());
            exeCodeRes.setCompilErrorMsg("编译错误：" + exeCompilRes);
            // 编译失败
            return exeCodeRes;
        }
        List<ExecuteResult> executeResultList = new LinkedList<>();

        Long maxTime = 0l;
        // 执行字节码文件
        for (String inputStr : inputList) {
            String exeCmd = String.format(execmdStringFormat, userCodeDir);
            ExecuteResult executeResult = processUtil.executeCompilCmd(exeCmd, inputStr);
            System.out.println(executeResult);
            executeResultList.add(executeResult);
            JudgeInfo judgeInfo = executeResult.getJudgeInfo();
            maxTime = Math.max(maxTime, judgeInfo.getTime());
        }
        // 删除目录
        processUtil.delCodeDir();
        // 设置程序执行数据
        exeCodeRes.setData(executeResultList);
        // 设置程序执行状态
        exeCodeRes.setStatus(ResponseCodeEnum.SUCCESS.getCode());
        return exeCodeRes;
    }
}
